use anyhow::Context;
pub use serde_json::json;
use serde::{Serialize, Deserialize};
use serde_json::Value;
use crate::encrypted::yb_encryptor::encrypt_form;

/// 创建提交日报所用的表单
/// ```rust
/// #[tokio::test]
///     async fn submit_test() -> anyhow::Result<()> {
///         let extend = FormExtend {
///             task_id: "751b11b050677c85bdf35decd79a8f14",
///             title: "任务信息",
///             content: vec![
///                 Content {
///                     label: "任务名称",
///                     value: "0908本科生健康动态日报",
///                 },
///                 Content {
///                     label: "发布机构",
///                     value: "学生工作处",
///                 },
///             ],
///         };
///         let form = TaskForm::default("b7b79316f5b732610023d987ec950577",
///                                      "b424f4428280af80c036a0bc9f28139e",
///                                      json!(
///                               {
///     "a069e4b52079413679cc71a8f70c7edf": "正常在校",
///     "98205659930dc79306b3c41ede65f239":{"name":"南京师范大学仙林校区北苑1111栋学生公寓",
///                                   "location":"88.913978,99.114609",
///                                       "address":"火星"},
///     "303558fbc358e7fccdb9a1e258606ffc": [
///         "体温正常，身体健康（37.3°以下）"
///     ],
///     "664d3c096eefcdc6f80e35b1c701a227": "36.6°-36.9°（正常体温）",
///     "7bdcea686bff26915e91ce77034de2b3": "体温正常，身体健康（37.3°以下）"
/// }
///                           ), extend);
///         let yb_client = Client::new("****", "*****");
///         let data = yb_client.base_post(&format!("https:///api.uyiban.com/workFlow/c/my/apply/b7b79316f5b732610023d987ec950577", ),
///                                        &[
///                                            ("CSRF", yb_client.cookie.get(CSRF_TOKEN).unwrap().as_str())
///                                        ], &[("Str", &form.encrypted()?)])
///             .await?
///             .text()
///             .await?;
///         println!("{:#?}", data);
///         Ok(())
///     }
/// ```
#[derive(Serialize, Deserialize, Debug)]
pub struct TaskForm<'a> {
    #[serde(rename = "WFId")]
    pub(crate) wf_id: &'a str,
    #[serde(rename = "Data")]
    data: Value,
    #[serde(rename = "WfprocessId")]
    wf_process_id: &'a str,
    #[serde(rename = "Extend")]
    extend: FormExtend<'a>,
    #[serde(rename = "CustomProcess")]
    custom_process: Value,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FormExtend<'a> {
    #[serde(rename = "TaskId")]
    pub task_id: &'a str,

    #[serde(rename = "title")]
    pub title: &'a str,

    #[serde(rename = "content")]
    pub content: Vec<Content<'a>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Content<'a> {
    #[serde(rename = "label")]
    pub label: &'a str,

    #[serde(rename = "value")]
    pub value: &'a str,
}

impl TaskForm<'_> {
    pub fn default<'a>(wf_id: &'a str, wf_process_id: &'a str, data: Value, extend: FormExtend<'a>) -> TaskForm<'a> {
        TaskForm {
            wf_id,
            data,
            wf_process_id,
            extend,
            custom_process: json!(
                {"ApplyPersonIds":[],"CCPersonId":[]}
            ),
        }
    }
    /// 转为易班采用的data格式
    pub fn form_string(&self) -> String {
        let data = serde_json::to_string(&self.data).unwrap();
        let extend = serde_json::to_string(&self.extend).unwrap();
        let custom_process = serde_json::to_string(&self.custom_process).unwrap();
        let str: Value = json!({
           "WFId":self.wf_id,
            "Data":data,
            "WfprocessId":self.wf_process_id,
             "Extend":extend,
            "CustomProcess":custom_process,
        });
        str.to_string()
    }
    pub fn encrypted(&self) -> anyhow::Result<String> {
        let data = encrypt_form(b"2knV5VGRTScU7pOq", b"UmNWaNtM0PUdtFCs", self.form_string().as_bytes())
            .with_context(|| String::from("数据加密失败"))?;
        let data = base64::encode(data);
        let data = base64::encode(data);
        Ok(data)
    }
}

#[cfg(test)]
mod task_form_test {
    use serde_json::json;
    use crate::module::task::{Content, FormExtend, TaskForm};

}